package net.apecloud.plugin.util;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * JavaScript混淆加密工具
 *
 * @author YuanShuai[apeblog@163.com]
 */
public class ObfuscateUtil {

    public static String obfuscate(String jsCode) {

        try (Context context = Context.create()) {
            // 加载混淆加密依赖文件
            context.eval("js", getContentByResource("dependent/javascript-obfuscate.js"));

            // 预定义混淆加密方法
            context.eval("js", getContentByResource("dependent/obfuscate.js"));
            // 获取JavaScript中的方法
            Value jsFunction = context.getBindings("js").getMember("exeObfuscate");
            return jsFunction.execute(jsCode).asString();
        } catch (Exception e){
            e.printStackTrace();
        }
        return jsCode;
    }

    private static String getContentByResource(String resourcePath) throws IOException {
        ClassPathResource resource  = new ClassPathResource(resourcePath);
        // 获取文件的输入流
        InputStream inputStream = resource.getInputStream();

        // 使用Scanner类读取输入流中的内容
        Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");

        // 将文件内容转换为字符串
        String fileContent = scanner.hasNext() ? scanner.next() : "";

        // 关闭Scanner和输入流
        scanner.close();
        inputStream.close();

        return fileContent;
    }

}
